package com.radon.service.impl;

import com.radon.config.MessagePostProcessorConfig;
import com.radon.config.RabbitSendConfirmHandler;
import com.radon.config.RabbitSendReturnback;
import com.radon.service.RabbitMQService;
import com.radon.util.Constant;
import com.radon.util.UniqueOrderGenerate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * RabbitMQ的service层，用于封装发送消息的方法
 */
@Service
public class RabbitMQServiceImpl implements RabbitMQService {

    private static Logger logger = LoggerFactory.getLogger(RabbitMQServiceImpl.class);
    //雪花算法对象
    private static UniqueOrderGenerate idWorker = new UniqueOrderGenerate(0, 0);
    //时间格式转换
    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /**
     * 消息队列模板
     */
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired //支持可靠性投递
    private RabbitSendConfirmHandler rabbitSendConfirmHandler;
    @Autowired//错误处理
    private RabbitSendReturnback rabbitSendReturnback;
    @Autowired//消息扩展器
    private MessagePostProcessorConfig messagePostProcessorConfig;



    @Override
    public void send(Object message, Constant.ExchangeEnum exchangeEnum, Constant.RoutingKeyEnum routingKeyEnum) {
        Long id = idWorker.get();
        logger.info("id"+id);
        //请求头参数
        Map<String, Object> properties =new HashMap<>();
        properties.put("id",id);
        properties.put("send_time", simpleDateFormat.format(new Date()));
        //设置请求头等属性
        MessageHeaders mhs = new MessageHeaders(properties);
        //创建消息的核心内容
        Message mes = MessageBuilder.createMessage(message, mhs);

        //这样可以支持消息的确认模式和返回模式
        //设置回调为当前类对象
        rabbitTemplate.setConfirmCallback(rabbitSendConfirmHandler);
        //设置发送失败
        rabbitTemplate.setReturnCallback(rabbitSendReturnback);
        //设置消息序列化模式
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        //构建id
        CorrelationData correlationId = new CorrelationData(id+"");
        //发送消息到消息队列
        rabbitTemplate.convertAndSend(exchangeEnum.getValue(),routingKeyEnum.getValue(),mes,messagePostProcessorConfig,correlationId);

    }


}
